const TopClient = require('../topClient').ApiClient;
const Promise = require('bluebird');
const axios = require('axios');

module.exports = function (config) {
  let captureHosts = config.captureHosts;
  let webservice_key = config.webservice_key;
  let taobaoConfig = config.taobao.tbk;
  let client = new TopClient({
    'appkey': taobaoConfig.app_key,
    'appsecret': taobaoConfig.app_secret,
    'REST_URL': 'http://gw.api.taobao.com/router/rest'
  });

  return {
    getTkl: function (body) {
      return new Promise(function (resolve) {
        let time = new Date().getTime();
        client.execute('taobao.tbk.tpwd.create', body, function (error, response) {
          if (error) {
            console.error('Api 生成口令错误', body, error);
            return resolve({});
          }

          console.log('Api 生成口令时间:', (new Date().getTime() - time));
          return resolve(response && response.data || {});
        });
      });
    },

    parseTkl: function (text) {
      return new Promise(function (resolve) {
        let time = new Date().getTime();
        client.execute('taobao.wireless.share.tpwd.query', {'password_content': text}, function (error, response) {
          if (error) {
            console.error('Api 解析口令错误', text, response);

            let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
            return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=taokouling&method=restore', {kouling: text}).then(function (response) {
              let result = response.data;
              if (result.success && result.data) {

                console.log('Api 解析口令时间:', (new Date().getTime() - time));
                return resolve(result.data);
              }
              console.error('taokouling 解密口令错误', result);
              return resolve({});
            }).catch(function (err) {
              if (err) {
                console.error('\n', err.stack || err.message);
              }
              return resolve({});
            });
          }

          console.log('Api 解析口令时间:', (new Date().getTime() - time));
          return resolve(response);
        });
      });
    },

    getMaterial: function (id, title) {
      let time = new Date().getTime();
      return new Promise(function (resolve) {
        client.execute('taobao.tbk.dg.material.optional', {
          'q': title,
          'adzone_id': '388088906',
          'page_size': 100,
        }, function (err, response) {
          if (err) {
            console.error('\n', err.stack || err.message);
            return resolve();
          }
          if (response.result_list && response.result_list.map_data) {
            let rows = response.result_list.map_data;
            for (let i in rows) {
              let row = rows[i];
              if (row.num_iid == id) {
                console.log('api 获取商品时间:', (new Date().getTime() - time));

                return resolve({
                  commission: (row.commission_rate / 100).toFixed(2),
                  commissionType: row.commission_type,
                  activityId: row.coupon_id,
                  couponEffectiveEndTime: row.coupon_end_time && (row.coupon_end_time + ' 23:59:59'),
                  couponEffectiveStartTime: row.coupon_start_time,
                  couponInfo: row.coupon_info,
                  couponLeftCount: row.coupon_remain_count,
                  couponTotalCount: row.coupon_total_count,
                  tkMktStatus: (row.include_mkt && row.include_mkt == 'true') ? 1 : 0,
                  includeDxjh: (row.include_dxjh && row.include_dxjh == 'true') ? 1 : 0,
                  infoDxjh: row.info_dxjh,
                  auctionId: row.num_iid,
                  pictUrl: row.pict_url,
                  provcity: row.provcity,
                  reservePrice: row.reserve_price,
                  sellerId: row.seller_id,
                  shopTitle: row.shop_title,
                  title: row.title,
                  userType: row.user_type,
                  zkPrice: row.zk_final_price,
                  biz30day: row.volume
                });
              }
            }
          }
          console.error('api 获取商品失败', response.total_results);
          return resolve();
        });
      });
    },

    getGoods: function (id) {
      let time = new Date().getTime();
      let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
      let action = 'alimama', method = 'findOne';
      return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=' + action + '&method=' + method, {
        url: 'https://item.taobao.com/item.htm?id=' + id
      }).then(function (response) {
        return response.data;
      }).catch(function (err) {
        if (err) {
          console.error('\n', err.stack || err.message);
        }
        return {success: false};
      }).then(function (result) {
        if (result.success && result.data) {
          console.log('alimama 获取商品时间:', (new Date().getTime() - time), result.data);
          return result.data;
        }
        console.error('alimama 获取商品失败', result);
      });
    },

    getCoupon: function (id, activityId) {
      return new Promise(function (resolve) {
        let time = new Date().getTime();
        client.execute('taobao.tbk.coupon.get', {
          'item_id': id,
          'activity_id': activityId
        }, function (error, response) {
          if (error) {
            console.error('Api 获取优惠券错误', response);
            return resolve({});
          }
          let data = response && response.data;
          if (data) {
            console.log('Api 获取优惠券时间:', (new Date().getTime() - time));
            return resolve({
              couponAmount: data.coupon_amount,
              couponEffectiveEndTime: data.coupon_end_time && (data.coupon_end_time + ' 23:59:59'),
              couponLeftCount: data.coupon_remain_count,
              couponStartFee: data.coupon_start_fee,
              couponEffectiveStartTime: data.coupon_start_time,
              couponTotalCount: data.coupon_total_count
            });
          }
          console.error('api 获取优惠券失败', response);
          return resolve();
        });
      });
    }
  };
}
